<template>
    <div>

        <!-- 添加会员卡统计容器 -->
        <div class="card-statistics">
            <div ref="chart" style="width: 1000px; height: 600px;"></div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import * as echarts from 'echarts'; // 引入 ECharts
import axios from "axios";

// 定义饼图数据
const pieData = ref([]);

// 获取数据
const fetchData = async () => {
    try {
        const response = await axios.get('http://localhost:8080/member/list?page=1&size=100');
        const data = response.data;

        // 解析数据
        const cardCounts = {};
        data.data.list.forEach(item => {
            item.memberCards.forEach(card => {
                const cardName = card.name;
                if (!cardCounts[cardName]) {
                    cardCounts[cardName] = 0;
                }
                cardCounts[cardName] += 1;
            });
        });

        // 构建数据结构
        Object.entries(cardCounts).forEach(([cardName, count]) => {
            pieData.value.push({ value: count, name: cardName });
        });
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};

// 初始化饼图
const chart = ref(null); // 添加 ref

const initChart = (data) => {
    const chartInstance = echarts.init(chart.value); // 使用 ref
    chartInstance.setOption({
        title: {
            text: '会员卡统计',
            subtext: '绑定会员卡数量',
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
            top: 'bottom'
        },
        toolbox: {
            show: true,
            feature: {
                mark: {show: true},
                dataView: {show: true, readOnly: false},
                restore: {show: true},
                saveAsImage: {show: true}
            }
        },
        series: [
            {
                name: 'Nightingale Chart',
                type: 'pie',
                radius: [50, 200],
                center: ['50%', '50%'],
                roseType: 'area',
                itemStyle: {
                    borderRadius: 10
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '20',
                        fontWeight: 'bold'
                    }
                },
                data: data
            }
        ]
    });
};

// 在组件挂载完成后获取数据并初始化图表
onMounted(async () => {
    await fetchData();
    initChart(pieData.value);
});
</script>

<style lang="less" scoped>
ul {
    list-style-type: none;
    padding-left: 0;
}

li {
    margin-bottom: 10px;
}

.card-statistics {
    background-color: white;
    width: 1050px;
    text-align: center;
    margin-left: 18px;
    margin-top: 30px;
    padding: 20px;
    
    h2 {
        margin-bottom: 10px;
    }
}
</style>